package io.gitee.yth.design.pattern.test.core.pattern.behavioral.observer.chman;

import io.gitee.yth.design.pattern.test.core.pattern.behavioral.observer.IObserver;
import io.gitee.yth.design.pattern.test.core.pattern.behavioral.observer.ISubject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * IChangeManager的实现：SimpleChangeManager、DAGChangeManager、...
 * <p>
 * 使用单例模式
 * <p>
 * 使用map可以更高效地进行更新
 *
 * @author yth
 * @since 2023-04-30-15:58
 */
public class ChangeManager implements IChangeManager {

    private static final ChangeManager instance = new ChangeManager();

    public static ChangeManager getInstance() {
        return instance;
    }

    private ChangeManager() {
    }

    private final Map<ISubject, List<IObserver>> map = new HashMap<>();

    @Override
    public void register(ISubject subject, IObserver observer) {
        Objects.requireNonNull(subject);
        Objects.requireNonNull(observer);
        List<IObserver> list = map.computeIfAbsent(subject, k -> new ArrayList<>());
        list.add(observer);
    }

    @Override
    public void unregister(ISubject subject, IObserver observer) {
        Objects.requireNonNull(subject);
        Objects.requireNonNull(observer);
        final List<IObserver> observers = map.get(subject);
        if (observers != null) {
            observers.remove(observer);
        }
    }

    @Override
    public void notifyObservers(ISubject subject) {
        final List<IObserver> observers = map.get(subject);
        if (observers != null) {
            observers.forEach(e -> e.update(subject));
        }
    }
}
